<?php

namespace App\Http\Model;

use App\Http\Controllers\PublicController;
use Illuminate\Database\Eloquent\Model;

class ProductModel extends Model
{
    protected $table = 'pre_product';
    protected $fillable = ['name', 'category_id', 'sort', 'states', 'content'];

    public function tag()
    {
        return $this->hasMany("App\Http\Model\ProductTagModel", "product_id");
    }

    public function sku()
    {
        return $this->hasMany("App\Http\Model\SkuModel", "product_id");
    }

    public function getProductList($limit)
    {

        $product = ProductModel::where("states", "!=", DELETE_STATUS)->paginate($limit);

        return $product;
    }

    public function addProduct($product, $tag, $sku)
    {

        \DB::beginTransaction();

        try {
            $product = (array)$product;

            $nameRes = ProductModel::where("name", $product["name"])->first();

            if (!empty($nameRes)) {
                return "商品已存在";
            }

            $p_id = $this->saveProduct($product, INSERT);

            foreach ($tag as $i) {
                if($this->saveTag($i, $p_id, INSERT)=="error"){
                    return"标签错误";
                }
            }

            foreach($sku as $s){
                if ($this->saveSku($s, $p_id, INSERT) == "error") {
                    return "库存错误";
                }
            }

            \DB::commit();

            return "success";
        } catch (Exception $e) {
            \DB::rollback();
            return "error";
        }
    }

    public function updateProduct($id, $product, $tag, $sku)
    {

        \DB::beginTransaction();

        try {
            $product = (array)$product;

            $nameRes = ProductModel::where("id", $id)->first();

            if (empty($nameRes)) {
                return "更新商品不存在";
            }

            $this->saveProduct($product,UPDATE,$id);

            ProductTagModel::where("product_id", $id)->update(["states" => 9]);

            SkuModel::where("product_id", $id)->update(["states" => 9]);

            foreach ($tag as $i) {

                $i = (array)$i;

                $act = array_key_exists("id",$i)?UPDATE:INSERT;

                if($this->saveTag($i,$id,$act)=="error"){
                    return "更新标签错误";
                }

            }

            foreach ($sku as $s) {

                $s = (array)$s;

                $act = array_key_exists("id", $s)?UPDATE:INSERT;

                if($this->saveSku($s,$id,$act)=="error"){

                    return "更新库存错误";

                }
            }

            \DB::commit();

            return "success";
        } catch (Exception $e) {
            \DB::rollback();
            return "error";
        }
    }

    public function delProduct($id)
    {
        $res = ProductModel::find($id);

        if(empty($res)){
            return "商品不存在";
        }

        $res->states = DELETE_STATUS;

        $res->save();

        if($res["id"]){
            return "success";
        }

        return "删除失败";
    }

    public function selectProduct($id)
    {
        $selectRes = ProductModel::where("id", $id)
            ->where("states","!=",DELETE_STATUS)
            ->with(["tag" => function ($query){
                $query->select('id','tag_id','value','product_id')
                      ->where("states", "!=", DELETE_STATUS)
                      ->with(["Img"=>function($query){
                        $query->select("id","file","imgId");
                    }]);
            },"sku"=>function($query){
                $query->where("states","!=",DELETE_STATUS)
                    ->select("id","product_id","original_price","price","attr1","attr2","attr3","quantity","sort","states");
            }])
            ->first();

        if(empty($selectRes)){
            return $selectRes;
        }

        foreach($selectRes->tag as $k=>$v){
            if($v["tag_id"]==1) {
                $v["value"] = "public".$v["img"]["file"];
            }
            unset($selectRes->tag[$k]["Img"]);
        }

        foreach($selectRes->sku as $k =>$a){
            $attrArr = array();
            for($i=1;$i<=3;$i++){
                $attrArr = $this->getAttrArr($attrArr, "attr".$i , $a["attr$i"]);
                $selectRes->sku[$k]["attr"] = $attrArr;
                unset($selectRes->sku[$k]["attr$i"]);
            }
//            $attrArr = $this->getAttrArr($attrArr, "attr2", $a['attr2']);
//            $attrArr = $this->getAttrArr($attrArr, "attr3", $a['attr3']);
//            unset($selectRes->sku[$k]["attr2"]);
//            unset($selectRes->sku[$k]["attr3"]);
        }
        return $selectRes;

    }

    private function getAttrArr($attrArr, $attrk, $attrv)
    {

        if (!is_null($attrv)) {
            $attrArr[$attrk] = $attrv;
        }
        return $attrArr;
    }

    private function doSave($data,$p_id){
        foreach($data as $s){
            if ($this->saveSku($s, $p_id, INSERT) == "error") {
                return "error";
            }
        }
    }

    private function saveProduct($product, $act,$id=null)
    {
        switch ($act) {
            case INSERT:
                $p_save = new ProductModel();
                break;
            case UPDATE:
                $p_save = ProductModel::where("id", $id)->first();
                if (empty($p_save)) {
                    return "商品不存在";
                }
                break;
        }
        $p_save['category_id'] = $product["category_id"];
        $p_save['name'] = $product["name"];
        $p_save['sort'] = $product["sort"];
        $p_save['states'] = $product["states"] == true ? 1 : 0;
        $p_save['content'] = $product["content"];
        $time = date("Y-m-d H:i:s");
        $p_save['created_at'] = $time;
        $p_save['updated_at'] = $time;
        $p_save->save();
        $p_id = $p_save["id"];
        return $p_id;
    }

    private function saveSku($s,$product_id,$act){

        $s = (array)$s;
        switch($act) {
            case INSERT:
                $sku = new SkuModel();
                break;
            case UPDATE:
                $sku = SkuModel::find($s["id"]);
        }
        try{
            foreach ($s["attr"] as $k => $a) {
                $sku->$k = $a;
            }
            $sku->product_id = $product_id;
            $sku->original_price = $s["original_price"];
            $sku->price = $s["price"];
            $sku->quantity = $s["quantity"];
            $sku->sort = $s["sort"];
            $sku->states = $s["states"];
            $sku->save();
            if(empty($sku)){
                return "error";
            }
        }catch (Exception $e){
            return "error";
        }

        return "success";

    }

    private function saveTag($tag, $product_id, $act)
    {
        switch ($act) {

            case INSERT:

                $pm = new ProductTagModel();

                break;
            case UPDATE:

                $pm = ProductTagModel::find($tag["id"]);

                break;
        }
        try {

            $i = (array)$tag;

            $pm->product_id = $product_id;

            $pm->states = 1;

            $pm->tag_id = $i["tag_id"];

            if ($i["tag_id"] == 1  and ((explode("/", $i["value"]))[0] == "tmp")) {

                $im = new ImgModel();

                $uc = new PublicController();

                $uuid = $uc->moveImg($i["value"]);

                $im->imgId = $uuid;

                $im->file = date("/Y/m/d/") . (explode("/", $i["value"])[1]);

                $im->save();

                $pm->value = $uuid;

            } else if($i["tag_id"]!=1){

                $pm->value = $i["value"];

            }

            $pm->save();

            if(empty($pm)){

                return "error";

            }

            return $pm["id"];

        }catch (Exception $e) {

            return "error";

        }
    }
}
